package org.gwu.seuss.util;

import java.io.InputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.Properties;

import org.springframework.jdbc.datasource.DriverManagerDataSource;

public class JdbcHelper {

	private static CredentialsHelper credentialsHelper = new ConsoleCredentialsHelper();
	private static String propertiesFile = "backend.properties";
	
	
	public static void setCredentialsHelper(CredentialsHelper credentialsHelper){
		JdbcHelper.credentialsHelper = credentialsHelper;
	}
	
	public static void setPropertiesFile(String propertiesFile){
		JdbcHelper.propertiesFile = propertiesFile;
	}
	
	public static DriverManagerDataSource getDataSource(){
	
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		
		ClassLoader classLoader = DriverManagerDataSource.class.getClassLoader();
		URL url = classLoader.getResource(propertiesFile);
		
		Properties props = new Properties();
		char[] password = null;
		char[] username = null;
		try(InputStream is = url.openStream();){
		
			props.load(is);
			
			dataSource.setDriverClassName(props.getProperty("driverClassName"));
			dataSource.setUrl(props.getProperty("url"));
			
			username = JdbcHelper.credentialsHelper.getDatabaseUserName();
			dataSource.setUsername(String.copyValueOf(username));
			
			password = JdbcHelper.credentialsHelper.getDatabasePassword();
			dataSource.setPassword(String.copyValueOf(password));
			
			dataSource.setConnectionProperties(props);

		}catch(Exception ex){
			throw new IllegalStateException("Unable to initialize database connection");
		}finally{
			
			if(username != null){
				Arrays.fill(username, ' ');
			}
			
			if(username != null){
				Arrays.fill(password, ' ');
			}
		}
		
		return dataSource;
		
	}
	
}
